using System;
using NFreeMarker.Template;

namespace NFreeMarker.Ext.Beans
{
    /**
     * @author Attila Szegedi
     * @version $Id: CollectionAdapter.java,v 1.2 2005/06/12 19:03:04 szegedia Exp $
     */
    class CollectionAdapter : ITemplateModelAdapter // TODO: AbstractCollection
    {
        private readonly BeansWrapper _wrapper;
        private readonly ITemplateCollectionModel _model;

        internal CollectionAdapter(ITemplateCollectionModel model, BeansWrapper wrapper)
        {
            _model = model;
            _wrapper = wrapper;
        }
        
        public ITemplateModel GetTemplateModel()
        {
            return _model;
        }
        
        public int Size()
        {
            throw new NotSupportedException();
        }

        //public Iterator Iterator()
        //{
        //    try
        //    {
        //        return new IteratorImpl(this);
        //    }
        //    catch(TemplateModelException e)
        //    {
        //        throw new UndeclaredThrowableException(e);
        //    }
        //}

        private class IteratorImpl
        {
            private readonly CollectionAdapter _collectionAdapter;
            readonly ITemplateModelIterator _i;

            public IteratorImpl(CollectionAdapter collectionAdapter)
            {
                _collectionAdapter = collectionAdapter;
                _i = _collectionAdapter._model.Iterator();
            }

            public bool HasNext()
            {
                try
                {
                    return _i.HasNext();
                }
                catch (TemplateModelException e)
                {
                    //throw new UndeclaredThrowableException(e);
                    throw new NotImplementedException();
                }
            }
            
            public object Next()
            {
                try
                {
                    return _collectionAdapter._wrapper.Unwrap(_i.Next());
                }
                catch(TemplateModelException e)
                {
                    //throw new UndeclaredThrowableException(e);
                    throw new NotImplementedException();
                }
            }
            
            public void Remove()
            {
                throw new NotSupportedException();
            }
        }
    }
}